import request from '../../utils/request';
let isSend = false;
Page({
  data: {
    placeholderContent: '',
    hotList: [],
    searchContent: '',
    searchList: [], // 歌曲搜索结果
    artistList: [], // 歌手搜索结果
    historyList: [],
  },

  // 页面加载时初始化数据
  onLoad(options) {
    this.getInitData();
    this.getSearchHistory();
  },

  // 获取初始数据（热搜榜和默认搜索词）
  async getInitData() {
    let placeholderData = await request('/search/default');
    let hotListData = await request('/search/hot/detail');
    this.setData({
      placeholderContent: placeholderData.data.showKeyword,
      hotList: hotListData.data,
    });
  },

  // 获取本地历史记录
  getSearchHistory() {
    let historyList = wx.getStorageSync('searchHistory');
    if (historyList) {
      this.setData({
        historyList,
      });
    }
  },

  // 输入框内容变化时触发
  handleInputChange(event) {
    this.setData({
      searchContent: event.detail.value.trim(),
    });
    if (isSend) return;
    isSend = true;
    // 节流
    this.getSearchList();
    setTimeout(() => {
      isSend = false;
    }, 300);
  },

  // 获取搜索结果
  async getSearchList() {
    if (!this.data.searchContent) {
      this.setData({
        searchList: [],
        artistList: [],
      });
      return;
    }
    let { searchContent, historyList } = this.data;
    // 搜索歌曲
    let searchListData = await request('/search', { keywords: searchContent, limit: 6, type: 1 });
    // 搜索歌手
    let artistListData = await request('/search', { keywords: searchContent, limit: 6, type: 100 });
    this.setData({
      searchList: searchListData.result.songs || [],
      artistList: artistListData.result.artists || [],
    });
    // 更新搜索历史
    if (historyList.indexOf(searchContent) !== -1) {
      historyList.splice(historyList.indexOf(searchContent), 1);
    }
    historyList.unshift(searchContent);
    this.setData({
      historyList,
    });
    wx.setStorageSync('searchHistory', historyList);
  },

  // 清除搜索内容
  clearSearchContent() {
    this.setData({
      searchContent: '',
      searchList: [],
      artistList: [],
    });
  },

  // 删除搜索历史
  deleteSearchHistory() {
    wx.showModal({
      content: '确认删除吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            historyList: [],
          });
          wx.removeStorageSync('searchHistory');
        }
      },
    });
  },

  // 点击歌曲跳转到歌曲详情页
  handleSongTap(event) {
    const songId = event.currentTarget.dataset.id;
    if (songId) {
      wx.navigateTo({
        url: `/pages/Song/Song?ids=${songId}`,
      });
    }
  },

  // 点击歌手跳转到歌手详情页
  handleArtistTap(event) {
    const artistId = event.currentTarget.dataset.id;
    if (artistId) {
      wx.navigateTo({
        url: `/pages/Artists/Artists?id=${artistId}`,
      });
    }
  },
});